package com.yswy.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yswy.common.exception.LoginException;
import org.springframework.beans.factory.annotation.Value;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * token工具
 * 
 * @author chenxin
 *
 */
public class TokenTool {

	@Value("${token.sk}")
	private String tokenSk;
	public static String crtToken(String secret, Map<String, String> seeds, int unit, int amount) {
		Date issuedAtDate = Calendar.getInstance().getTime();
		Date expiresDate = null;
		if (unit != 0 && amount != 0) {
			Calendar nowTime = Calendar.getInstance();
			nowTime.add(unit, amount);
			expiresDate = nowTime.getTime();
		}
		// header Map
		Map<String, Object> map = new HashMap<>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");
		// build token
		Builder builder = JWT.create().withHeader(map);
		builder = builder.withClaim("iss", "Service").withClaim("aud", "APP");
		for (Entry<String, String> e : seeds.entrySet())// seeds
			builder = builder.withClaim(e.getKey(), e.getValue());
		if (expiresDate != null) {
			builder = builder.withIssuedAt(issuedAtDate)// sign time
					.withExpiresAt(expiresDate);// expire time
		} else
			builder = builder.withIssuedAt(issuedAtDate);
		String token = builder.sign(Algorithm.HMAC256(secret)); // signature
		return token;
	}

	public static String crtToken(String secret, Map<String, String> seeds) {
		return crtToken(secret, seeds, 0, 0);
	}

	public static Map<String, Claim> verifyToken(String token, String secret) {
		DecodedJWT jwt = null;
		JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
		jwt = verifier.verify(token);


		return jwt.getClaims();
	}

	public static void main(String[] args) {



		//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJBUFAiLCJpc3MiOiJTZXJ2aWNlIiwiaWQiOiIxMjM0NTYiLCJleHAiOjE2OTI4OTMxNjgsImlhdCI6MTY5MjYzMzk2OH0._0u1e2t9sWsxNXaAEAYy0KsradLgWxwP5g_3xCI_YlU
		Map<String, String> seeds = new HashMap<>();
		seeds.put("id" , "123456");
		String token = TokenTool.crtToken("123!@#$^&*(*(^%$&&**(dasdasde", seeds, Calendar.DATE, 3);
		System.out.println(token);

		Map<String, Claim> seedss = TokenTool.verifyToken(
				token
				, "HS512");
		Claim uid = seedss.get("id");
		System.out.println(uid.asString());
	}
}
